<?php
namespace app\index\controller;

use think\Request;
use think\Db;
use think\Controller;
use app\index\controller\Util;

class Weather extends Controller {
  //获取天气信息
  public function getClimateInfo() {
    $proarr = ['北京市', '上海市', '天津市', '重庆市']; 
    $request = Request::instance();
        if($request->isPost()){
          $data = $request->except(['name']);
          $equnique = $data['equnique'];
          $map = [
              'ID' =>  ['=', $equnique]
          ];
          $resdata = Db::table('published_seismic_database')->field('eqtname, province, abbreviation')->where($map)->select();
          $climate = Db::table('published_seismic_database')->field('climate')->where($map)->select();
          $clidescription = $climate[0];
          if(mb_substr($clidescription['climate'], mb_strlen($clidescription['climate'], 'utf-8')-1, mb_strlen($clidescription['climate'], 'utf-8'), 'utf-8') != "。") {
            $clidescription['climate'] = $clidescription['climate']."。";
          }
          if(!$resdata) return $this->packData(null);
          $res = $resdata[0];
          $pro = trim($res['province']);
          $name = trim($res['abbreviation']);
          if(in_array($pro, $proarr)) {
            $city = $pro;
          }else {
            $city = trim($res['eqtname']);
          }
        }
        $data = $this->getReadData($city, $clidescription, $name);
        $info = "成功获取天气信息！";
        $util = new Util();
        $util->sendLogInfo($info);
        if(isset($data['clidata']['error'])) {
          $city = $name; 
          $data = $this->getReadData($city, $clidescription, $name);
          return json_encode($data);
        } else {
          return json_encode($data);
        }      
  }
  protected function getReadData($city, $clidescription, $name){
      $url='http://wthrcdn.etouch.cn/WeatherApi?city='.$city;
      $ch = curl_init();
      $timeout = 5;
      curl_setopt($ch, CURLOPT_URL, $url);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
      curl_setopt($ch,CURLOPT_ENCODING ,'gzip');
      curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
      $file_contents = curl_exec($ch);
      curl_close($ch);
      $clidata=json_decode(json_encode(simplexml_load_string($file_contents, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
      $data = [
      'clidescription' => $clidescription,
      'clidata' =>  $clidata,
      'name' => $name
      ];
      return $data;
  }

}